<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div slot="header" ref="tableheader" class="clearfix">
        <el-tabs v-model="loginType" @tab-click="getList(1)">
          <el-tab-pane v-for="(item, index) in headeNum" :key="index" :label="$t(item.name)" :name="item.type.toString()" />
        </el-tabs>
        <div class="container">
          <el-form
            ref="userFrom"
            inline
            size="small"
            :model="userFrom"
            :label-position="labelPosition"
            label-width="100px"
          >
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <el-col v-bind="grid">
                  <el-form-item :label="$t('yongHuNiCheng')+'：'">
                    <el-input v-model="userFrom.keywords" :placeholder="$t('qingShuRuYongHuNiCheng')" clearable class="selWidth" />
                  </el-form-item>
                </el-col>
              </el-col>
              <template v-if="collapse">
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-form-item :label="$t('fangWenShiJian')+'：'">
                    <el-date-picker
                      v-model="timeVal"
                      align="right"
                      unlink-panels
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                      size="small"
                      type="daterange"
                      placement="bottom-end"
                      :start-placeholder="$t('kaiShiRiQi')"
                      :end-placeholder="$t('jieShuRiQi')"
                      class="selWidth"
                      :picker-options="pickerOptions"
                      @change="onchangeTime"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col v-bind="grid">
                    <el-form-item :label="$t('youXiang')+'：'">
                      <el-input
                        v-model="userFrom.email"
                        :placeholder="$t('tishi3')"
                        clearable
                        class="selWidth"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col v-bind="grid">
                    <el-form-item :label="$t('xingBie')+'：'">
                      <el-radio-group v-model="userFrom.sex" type="button" class="selWidth">
                        <el-radio-button label="">
                          <span>{{ $t('quanBu') }}</span>
                        </el-radio-button>
                        <el-radio-button label="0">
                          <span>{{ $t('weiZhi') }}</span>
                        </el-radio-button>
                        <el-radio-button label="1">
                          <span>{{ $t('nan') }}</span>
                        </el-radio-button>
                        <el-radio-button label="2">
                          <span>{{ $t('nv') }}</span>
                        </el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-col>
              </template>
              <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6" class="text-right userFrom">
                <el-form-item>
                  <el-button
                    type="primary"
                    icon="ios-search"
                    label="default"
                    class="mr15"
                    size="small"
                    @click="userSearchs"
                  >{{ $t('chaXun') }}</el-button>
                  <el-button class="ResetSearch mr10" size="small" @click="reset('userFrom')">{{ $t('reset') }}</el-button>
                  <a class="ivu-ml-8" @click="onCollapse">
                    <template v-if="!collapse"> {{ $t('zhanKai') }} <i class="el-icon-arrow-down" /> </template>
                    <template v-else> {{ $t('shouQi') }} <i class="el-icon-arrow-up" /> </template>
                  </a>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        :height="tableHeight"
        highlight-current-row
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item :label="$t('zhenShiXingMing')+'：'">
                <span>{{ props.row.realName | filterEmpty }}</span>
              </el-form-item>
              <el-form-item :label="$t('xingBie')+'：'">
                <span>{{ $t(sexFilter(props.row.sex)) }}</span>
              </el-form-item>
              <el-form-item :label="$t('shouCiFangWen')+'：'">
                <span>{{ props.row.createTime | filterEmpty }}</span>
              </el-form-item>
              <el-form-item :label="$t('jinCiFangWen')+'：'">
                <span>{{ props.row.lastLoginTime | filterEmpty }}</span>
              </el-form-item>
              <el-form-item :label="$t('beiZhu')+'：'">
                <span>{{ props.row.mark | filterEmpty }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="uid" label="ID" min-width="80" />
        <el-table-column :label="$t('touXiang')" min-width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.avatar"
                :preview-src-list="[scope.row.avatar]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkedCities.includes('niCheng')" :label="$t('niCheng')" min-width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.nickname | filterEmpty }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column-->
        <!--label="最近访问"-->
        <!--min-width="120"-->
        <!--&gt;-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{scope.row.lastLoginTime | filterEmpty}}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column :abel="$t('shouJiHao')" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.phone | filterEmpty }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('youXiang')" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.email | filterEmpty }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('yongHuLeiXing')" min-width="100">
          <template slot-scope="scope">
            <span>{{ $t(typeFilter(scope.row.userType)) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="nowMoney"
          label="余额"
          min-width="100"
          v-if="checkedCities.includes('余额')"
        /> -->
        <!-- <el-table-column
          prop="integral"
          label="积分"
          min-width="100"
          v-if="checkedCities.includes('积分')"
        /> -->
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[15, 30, 45, 60]"
          :page-size="userFrom.limit"
          :current-page="userFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <div v-show="card_select_show" class="card_abs" :style="{ top: collapse ? 570 + 'px' : 270 + 'px' }">
      <template>
        <div class="cell_ht">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >{{ $t('quanXuan') }}</el-checkbox>
          <el-button type="text" @click="checkSave()">{{ $t('baoCun') }}</el-button>
        </div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="item in columnData" :key="item" :label="item" class="check_cell">{{ $t(item) }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </div>
  </div>
</template>

<script>
import { userListApi } from '@/api/user'
import { spreadClearApi } from '@/api/distribution'
import userList from '@/components/userList'
import { checkPermi } from '@/utils/permission' // 权限判断函数
import { Debounce } from '@/utils/validate'
export default {
  name: 'UserIndex',
  data() {
    return {
      tableHeight: 0,
      formExtension: {
        image: '',
        spreadUid: '',
        userId: ''
      },
      ruleInline: {},
      extensionVisible: false,
      userVisible: false,
      levelInfo: '',
      pickerOptions: this.$timeOptions,
      loadingBtn: false,
      PointValidateForm: {
        integralType: 2,
        integralValue: 0,
        moneyType: 2,
        moneyValue: 0,
        uid: ''
      },
      loadingPoint: false,
      VisiblePoint: false,
      visible: false,
      userIds: '',
      dialogVisible: false,
      levelVisible: false,
      levelData: [],
      groupData: [],
      labelData: [],
      selData: [],
      labelPosition: 'right',
      collapse: false,
      props: {
        children: 'child',
        label: 'name',
        value: 'name',
        emitPath: false
      },
      propsCity: {
        children: 'child',
        label: 'name',
        value: 'name'
      },
      headeNum: [
        { type: '', name: 'quanBuYongHu' },
        { type: 'facebook', name: 'Facebook' },
        { type: 'twitter', name: 'Twitter' },
        { type: 'google', name: 'Google' },
        { type: 'email', name: 'Email' },
        { type: 'phone', name: 'Phone' },
        { type: 'visitor', name: 'youKe' }
      ],
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      loginType: '',
      userFrom: {
        // labelId: '',
        userType: '',
        sex: '',
        // accessType: 0,
        dateLimit: '',
        keywords: '',
        page: 1,
        limit: 15,
        email: ''
        // groupId: '',
        // status: null
      },
      grid: {
        xl: 8,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      levelList: [],
      labelLists: [],
      groupList: [],
      selectedData: [],
      timeVal: [],
      dynamicValidateForm: {
        groupId: []
      },
      loading: false,
      groupIdFrom: [],
      selectionList: [],
      batchName: '',
      uid: 0,
      Visible: false,
      keyNum: 0,
      address: [],
      multipleSelectionAll: [],
      idKey: 'uid',
      card_select_show: false,
      checkAll: false,
      checkedCities: ['ID', 'touXiang', 'niCheng', 'yongHuDengJi', 'fenZu', 'tuiJianRen', 'shouJiHao', 'yuE', 'jiFen'],
      columnData: ['ID', 'touXiang', 'niCheng', 'yongHuDengJi', 'fenZu', 'tuiJianRen', 'shouJiHao', 'yuE', 'jiFen'],
      isIndeterminate: true
    }
  },
  created() {
    // 浏览器高度
    const windowHeight = document.documentElement.clientHeight || document.body.clientHeight

    // 此处减去100即为当前屏幕内除了表格高度以外其它内容的总高度，
    // this.tableHeight = windowHeight - 388;
  },
  activated() {
    this.userFrom.keywords = ''
    this.loginType = '0'
    this.getList(1)
  },
  mounted() {
    this.getList()
    this.$nextTick(() => {
      const tableHeader = this.$refs.tableheader.offsetHeight
      this.tableHeight = this.$selfUtil.getTableHeight(tableHeader + 100)
    })
  },
  methods: {
    checkPermi,
    onCollapse() {
      this.collapse = !this.collapse
      this.$nextTick(() => {
        const tableHeader = this.$refs.tableheader.offsetHeight
        this.tableHeight = this.$selfUtil.getTableHeight(tableHeader + 150)
      })
    },
    typeFilter(value) {
      const statusMap = {
        facebook: 'Facebook',
        twitter: 'Twitter',
        google: 'Google',
        email: 'Email',
        phone: 'Phone',
        visitor: 'youKe'
      }
      return statusMap[value]
    },
    sexFilter(status) {
      const statusMap = {
        0: 'weiZhi',
        1: 'nan',
        2: 'nv',
        3: 'baoMi'
      }
      return statusMap[status]
    },
    // 清除
    // clearSpread(row) {
    //   this.$modalSure('解除【' + row.nickname + '】的上级推广人吗').then(() => {
    //     spreadClearApi(row.uid).then((res) => {
    //       this.$message.success('清除成功')
    //       this.getList()
    //     })
    //   })
    // },
    onSubExtension(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateSpreadApi(this.formExtension).then((res) => {
            this.$message.success(this.$t('sheZhiChengGong'))
            this.extensionVisible = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    getTemplateRow(row) {
      this.formExtension.image = row.avatar
      this.formExtension.spreadUid = row.uid
    },
    // setExtension(row){
    //   this.formExtension = {
    //       image: '',
    //       spreadUid: '',
    //       userId: row.uid
    //   };
    //   this.extensionVisible = true
    // },
    handleCloseExtension() {
      this.extensionVisible = false
    },
    modalPicTap() {
      this.userVisible = true
    },
    resetForm() {
      this.visible = false
    },
    reset(formName) {
      this.userFrom = {
        // labelId: '',
        userType: '',
        sex: '',
        // isPromoter: '',
        // country: '',
        email: '',
        // accessType: 0,
        dateLimit: '',
        keywords: '',
        // province: '',
        // city: '',
        page: 1,
        limit: 15
        // level: '',
        // groupId: ''
      }
      this.levelData = []
      this.groupData = []
      this.labelData = []
      this.timeVal = []
      this.getList()
    },
    // 发送文章
    sendNews() {
      if (this.selectionList.length === 0) return this.$message.warning(this.$t('qingXianXuanZeYongHu'))
      const _this = this
      this.$modalArticle(function(row) {}, 'send')
    },
    // 发送优惠劵
    onSend() {
      if (this.selectionList.length === 0) return this.$message.warning(this.$t('qingXuanZeYaoSheZhiDeYongHu'))
      const _this = this
      this.$modalCoupon(
        'send',
        (this.keyNum += 1),
        [],
        function(row) {
          _this.formValidate.give_coupon_ids = []
          _this.couponData = []
          row.map((item) => {
            _this.formValidate.give_coupon_ids.push(item.coupon_id)
            _this.couponData.push(item.title)
          })
          _this.selectionList = []
        },
        this.userIds,
        'user'
      )
    },
    Close() {
      this.Visible = false
      this.levelVisible = false
    },
    // 账户详情
    onDetails(id) {
      this.uid = id
      this.Visible = true
    },
    // 等级
    // onLevel(id,level){
    //   var userLevel = new Object();
    //   this.levelList.forEach(item=>{
    //     if(item.id == level){
    //       userLevel.gradeLevel = item.grade;
    //     }
    //   })
    //   userLevel.uid = id;
    //   userLevel.level = level;
    //   this.levelInfo = userLevel;
    //   this.levelVisible = true;
    // },
    // 积分余额
    editPoint(id) {
      this.uid = id
      this.VisiblePoint = true
    },
    // 积分余额
    submitPointForm: Debounce(function(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.PointValidateForm.uid = this.uid
          this.loadingBtn = true
          foundsApi(this.PointValidateForm)
            .then((res) => {
              this.$message.success(this.$t('sheZhiChengGong'))
              this.loadingBtn = false
              this.handlePointClose()
              this.getList()
            })
            .catch(() => {
              this.loadingBtn = false
            })
        } else {
          return false
        }
      })
    }),
    // 积分余额
    handlePointClose() {
      this.VisiblePoint = false
      this.PointValidateForm = {
        integralType: 2,
        integralValue: 0,
        moneyType: 2,
        moneyValue: 0,
        uid: ''
      }
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['dynamicValidateForm'].resetFields()
    },
    // 搜索
    userSearchs() {
      this.userFrom.page = 1
      this.getList()
    },
    // 选择国家
    changeCountry() {
      if (this.userFrom.country === 'OTHER' || !this.userFrom.country) {
        this.selectedData = []
        this.userFrom.province = ''
        this.userFrom.city = ''
        this.address = []
      }
    },
    // 选择地址
    handleChange(value) {
      this.userFrom.province = value[0]
      this.userFrom.city = value[1]
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e
      this.userFrom.dateLimit = e ? this.timeVal.join(',') : ''
    },
    // 列表
    getList(num) {
      this.listLoading = true
      this.userFrom.page = num || this.userFrom.page
      this.userFrom.userType = this.loginType
      if (this.loginType == 0) this.userFrom.userType = ''
      // this.userFrom.level = this.levelData.join(',')
      this.userFrom.groupId = this.groupData.join(',')
      this.userFrom.labelId = this.labelData.join(',')
      userListApi(this.userFrom)
        .then((res) => {
          this.tableData.data = res.list
          this.tableData.total = res.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
      this.checkedCities = this.$cache.local.has('user_stroge')
        ? this.$cache.local.getJSON('user_stroge')
        : this.checkedCities
      this.$set(this, 'card_select_show', false)
    },
    pageChange(page) {
      this.$selfUtil.changePageCoreRecordData(
        this.multipleSelectionAll,
        this.multipleSelection,
        this.tableData.data,
        (e) => {
          this.multipleSelectionAll = e
        }
      )
      this.userFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.$selfUtil.changePageCoreRecordData(
        this.multipleSelectionAll,
        this.multipleSelection,
        this.tableData.data,
        (e) => {
          this.multipleSelectionAll = e
        }
      )
      this.userFrom.limit = val
      this.getList()
    },
    renderHeader(h) {
      return (
        <p>
          <span style='padding-right:5px;'>{this.$t('caoZuo')}</span>
        </p>
      )
      // <i class="el-icon-setting" onClick={()=>this.handleAddItem()}></i>
    },
    handleAddItem() {
      if (this.card_select_show) {
        this.$set(this, 'card_select_show', false)
      } else if (!this.card_select_show) {
        this.$set(this, 'card_select_show', true)
      }
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.columnData : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.columnData.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnData.length
    },
    checkSave() {
      this.$modal.loading(this.$t('tishi2'))
      this.$cache.local.setJSON('user_stroge', this.checkedCities)
      setTimeout(this.$modal.closeLoading(), 1000)
    }
  }
}
</script>

<style scoped lang="scss">
// .timeBox{
//   width: 100%;
//   ::v-deep.el-form-item__content{
//     width: 87% !important;
//   }
// }
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.text-right {
  text-align: right;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.33%;
}
.selWidth {
  width: 100% !important;
}
.seachTiele {
  line-height: 30px;
}
.container {
  min-width: 821px;
  ::v-deepel-form-item {
    width: 100%;
  }
  ::v-deepel-form-item__content {
    width: 72%;
  }
}
.ivu-ml-8 {
  font-size: 12px;
  color: #1682e6;
}
.btn_bt {
  border-top: 1px dashed #ccc;
  padding-top: 20px;
}
.relative {
  position: relative;
}
.card_abs {
  position: absolute;
  padding-bottom: 15px;
  right: 40px;
  width: 200px;
  background: #fff;
  z-index: 99999;
  box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
}
.cell_ht {
  height: 50px;
  padding: 15px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #eeeeee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.check_cell {
  width: 100%;
  padding: 15px 20px 0;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #606266;
}
</style>
